from fastapi import APIRouter, HTTPException, Depends, Query
from typing import List, Optional
from api.models.schemas import (
    PeopleInfo, 
    PeopleWorkHoursResponse, 
    ApiResponse,
    WorkLogDetail
)
from database import get_query_helper, WorkHoursQueryHelper
from utils.logger import get_logger

# 获取日志记录器
logger = get_logger(__name__)

router = APIRouter()


def get_query_helper_dependency() -> WorkHoursQueryHelper:
    """获取查询辅助器的依赖注入"""
    return get_query_helper()


@router.get("/people", response_model=ApiResponse, summary="获取所有员工信息")
async def get_all_people(
    query_helper: WorkHoursQueryHelper = Depends(get_query_helper_dependency)
):
    """
    获取所有员工信息
    
    返回系统中所有员工的基本信息
    """
    try:
        logger.info("👥 获取所有员工信息")
        
        people_data = query_helper.get_all_people()
        
        # 转换为响应模型
        people_list = []
        for person in people_data:
            people_list.append(PeopleInfo(**person))
        
        logger.info(f"✅ 获取员工信息成功: {len(people_list)} 人")
        
        return ApiResponse(
            code=200,
            message="获取员工信息成功",
            data=people_list
        )
        
    except Exception as e:
        logger.error(f"❌ 获取员工信息失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取员工信息失败: {str(e)}")


@router.get("/people/{people_name}/worklogs", response_model=ApiResponse, summary="按员工查询工时")
async def get_people_worklogs(
    people_name: str,
    start_date: str = Query(..., description="开始日期 (YYYY-MM-DD)"),
    end_date: str = Query(..., description="结束日期 (YYYY-MM-DD)"),
    query_helper: WorkHoursQueryHelper = Depends(get_query_helper_dependency)
):
    """
    按员工查询工时
    
    根据员工姓名和时间范围查询工时记录
    """
    try:
        logger.info(f"👤 查询员工工时: {people_name}, {start_date} - {end_date}")
        
        # 获取员工工时记录
        work_logs = query_helper.get_people_worklogs(people_name, start_date, end_date)
        
        # 获取总工时
        total_hours = query_helper.get_people_total_hours(people_name, start_date, end_date)
        
        # 转换为响应模型
        work_log_details = []
        for log in work_logs:
            work_log_details.append(WorkLogDetail(**log))
        
        # 获取员工所属部门
        framework_name = None
        if work_logs:
            framework_name = work_logs[0].get('FrameworkName')
        
        response_data = PeopleWorkHoursResponse(
            people_name=people_name,
            framework_name=framework_name,
            total_hours=total_hours,
            work_logs=work_log_details
        )
        
        logger.info(f"✅ 员工工时查询完成: {len(work_logs)} 条记录, {total_hours:.1f} 小时")
        
        return ApiResponse(
            code=200,
            message="查询成功",
            data=response_data.dict()
        )
        
    except Exception as e:
        logger.error(f"❌ 员工工时查询失败: {e}")
        raise HTTPException(status_code=500, detail=f"查询失败: {str(e)}")


@router.get("/people/{people_name}/summary", response_model=ApiResponse, summary="员工工时总结")
async def get_people_summary(
    people_name: str,
    start_date: str = Query(..., description="开始日期 (YYYY-MM-DD)"),
    end_date: str = Query(..., description="结束日期 (YYYY-MM-DD)"),
    query_helper: WorkHoursQueryHelper = Depends(get_query_helper_dependency)
):
    """
    员工工时总结
    
    获取指定员工在指定时间范围内的工时统计总结
    """
    try:
        logger.info(f"📊 生成员工工时总结: {people_name}, {start_date} - {end_date}")
        
        # 获取员工工时记录
        work_logs = query_helper.get_people_worklogs(people_name, start_date, end_date)
        total_hours = query_helper.get_people_total_hours(people_name, start_date, end_date)
        
        # 生成统计信息
        summary = generate_people_summary(people_name, work_logs, total_hours, start_date, end_date)
        
        logger.info(f"✅ 员工工时总结生成完成: {people_name}")
        
        return ApiResponse(
            code=200,
            message="总结生成成功",
            data={
                "people_name": people_name,
                "start_date": start_date,
                "end_date": end_date,
                "total_hours": total_hours,
                "total_records": len(work_logs),
                "summary": summary
            }
        )
        
    except Exception as e:
        logger.error(f"❌ 员工工时总结生成失败: {e}")
        raise HTTPException(status_code=500, detail=f"总结生成失败: {str(e)}")


def generate_people_summary(people_name: str, work_logs: List, total_hours: float, start_date: str, end_date: str) -> str:
    """生成员工工时总结"""
    
    # 按项目统计
    project_stats = {}
    for log in work_logs:
        project_name = log.get('ProjectName', '未知项目')
        if project_name not in project_stats:
            project_stats[project_name] = {'hours': 0, 'logs': 0}
        project_stats[project_name]['hours'] += log.get('WorkHour', 0)
        project_stats[project_name]['logs'] += 1
    
    # 按工时类型统计
    work_type_stats = {}
    for log in work_logs:
        work_type = log.get('WorkHourType', '未知')
        if work_type not in work_type_stats:
            work_type_stats[work_type] = 0
        work_type_stats[work_type] += log.get('WorkHour', 0)
    
    # 生成总结
    summary = f"## {people_name} 工时统计总结\n\n"
    summary += f"**时间范围**: {start_date} 至 {end_date}\n\n"
    summary += f"**总体统计**:\n"
    summary += f"- 总工时: {total_hours:.1f} 小时\n"
    summary += f"- 总记录数: {len(work_logs)} 条\n"
    summary += f"- 日均工时: {total_hours / max(1, len(work_logs)):.1f} 小时\n\n"
    
    if project_stats:
        summary += "**项目工时分布**:\n"
        sorted_projects = sorted(project_stats.items(), key=lambda x: x[1]['hours'], reverse=True)
        for project, stats in sorted_projects:
            percentage = (stats['hours'] / total_hours * 100) if total_hours > 0 else 0
            summary += f"- {project}: {stats['hours']:.1f} 小时 ({percentage:.1f}%) - {stats['logs']} 条记录\n"
        summary += "\n"
    
    if work_type_stats:
        summary += "**工时类型分布**:\n"
        sorted_types = sorted(work_type_stats.items(), key=lambda x: x[1], reverse=True)
        for work_type, hours in sorted_types:
            percentage = (hours / total_hours * 100) if total_hours > 0 else 0
            summary += f"- {work_type}: {hours:.1f} 小时 ({percentage:.1f}%)\n"
        summary += "\n"
    
    summary += "**备注**: 此总结由系统自动生成。"
    
    return summary 